# _*_ coding:utf-8 _*_
# @File  : fifteen_quotes.py
# @Time  : 2021-12-30  08:27
# @Author: zizle


# 开盘15分钟K线涨跌分析
import json
import pathlib
from db import FAConnection
from fastapi import APIRouter, Query, Body
from utils.datetime_util import verify_datetime_format
from utils.char_reverse import split_number_en
from status import r_status
from category import VARIETY_NAME
from configs import APP_DIR

fifteen_quote_api = APIRouter()


@fifteen_quote_api.post('/', summary='保存15分钟涨跌数据')
async def save_fifteen_quote(quote_data: list = Body(...)):
    db_conn = FAConnection(conn_name='保存15分行情数据')
    sql = 'INSERT INTO dat_fifteen_quotes (quote_time,thscode,openp,closep) ' \
          'VALUES (%(quote_time)s,%(thscode)s,%(openp)s,%(closep)s);'
    _, success = db_conn.execute(sql, param=quote_data, many=True)
    if success:
        return {'code': r_status.CREATED_SUCCESS, 'message': '数据保存成功!'}
    else:
        return {'code': r_status.SERVER_ERROR, 'message': '数据保存失败!'}


def format_number(n, p=2):
    return int(n) if int(n) == float(n) else round(n, p)


def format_zd(item):
    item['zd'] = '%.2f%%' % item['zd']
    return item


@fifteen_quote_api.get('/zd/', summary='开盘15分钟涨跌')
async def fifteen_quote(date: str = Query(...)):
    f_date = verify_datetime_format(date)
    if not f_date:
        return {'code': r_status.VALIDATE_ERROR, 'message': '查询参数日期格式错误', 'data': []}
    query_sql = 'SELECT id,quote_time,thscode,openp,closep FROM dat_fifteen_quotes ' \
                'WHERE DATE_FORMAT(quote_time, "%%Y-%%m-%%d")=%s;'
    db_conn = FAConnection()
    records = db_conn.query(query_sql, param=[f_date])

    if len(records) < 1:
        return {'code': r_status.NOT_CONTENT, 'message': '没有数据!', 'data': []}
    # 处理数据计算涨跌
    quote_contracts = []

    start_quotes = []
    middle_quotes = []
    end_quotes = []
    for item in records:
        flg_time = item['quote_time'].strftime('%H:%M')
        ths_code = item['thscode'].split('.')
        contract = split_number_en(ths_code[0])
        item['quote_time'] = item['quote_time'].strftime('%Y-%m-%d %H:%M:%S')
        item['contract_name'] = VARIETY_NAME.get(contract[0], contract[0]) + contract[1]
        item['openp'] = format_number(item['openp'])
        item['closep'] = format_number(item['closep'])

        item['zd'] = round((item['closep'] / item['openp'] - 1) * 100, 2)
        quote_contracts.append(item['thscode'])

        if flg_time == '09:15':
            start_quotes.append(item)
        elif flg_time == '13:45':
            middle_quotes.append(item)
        elif flg_time == '21:15':
            end_quotes.append(item)
        else:
            pass

    # 排序
    start_quotes.sort(key=lambda x: x['zd'], reverse=True)
    middle_quotes.sort(key=lambda x: x['zd'], reverse=True)
    end_quotes.sort(key=lambda x: x['zd'], reverse=True)

    start_quotes = list(map(format_zd, start_quotes))
    middle_quotes = list(map(format_zd, middle_quotes))
    end_quotes = list(map(format_zd, end_quotes))

    filepath = pathlib.Path(APP_DIR).joinpath('tasks/control_files/fifteen_quotes.json')
    with open(filepath, 'rb') as fp:
        fifteen_quote_config = json.load(fp)

    start_contract = [i['thscode'] for i in start_quotes]
    middle_contract = [i['thscode'] for i in middle_quotes]
    end_contract = [i['thscode'] for i in end_quotes]

    start_no_exist = list(set(fifteen_quote_config['contracts']) - set(start_contract))
    middle_no_exist = list(set(fifteen_quote_config['contracts']) - set(middle_contract))
    end_no_exist = list(set(fifteen_quote_config['contracts']) - set(end_contract))

    for c in start_no_exist:
        contract = split_number_en(c.split('.')[0])
        contract_name = VARIETY_NAME.get(contract[0], contract[0]) + contract[1]
        start_quotes.append({'id': -1, 'thscode': c, 'quote_time': f'{f_date} 09:15:00', 'openp': '-', 'closep': '-', 'zd': '-',
                             'contract_name': contract_name})

    for c in middle_no_exist:
        contract = split_number_en(c.split('.')[0])
        contract_name = VARIETY_NAME.get(contract[0], contract[0]) + contract[1]
        middle_quotes.append({'id': -1, 'thscode': c, 'quote_time': f'{f_date} 13:45:00', 'openp': '-', 'closep': '-', 'zd': '-',
                              'contract_name': contract_name})

    for c in end_no_exist:
        contract = split_number_en(c.split('.')[0])
        contract_name = VARIETY_NAME.get(contract[0], contract[0]) + contract[1]
        end_quotes.append({'id': -1, 'thscode': c, 'quote_time': f'{f_date} 21:15:00', 'openp': '-', 'closep': '-', 'zd': '-',
                           'contract_name': contract_name})

    return {'code': r_status.SUCCESS, 'message': '查询前15分钟涨跌数据成功!', 'query_date': f_date,
            'morning': start_quotes, 'afternoon': middle_quotes, 'evening': end_quotes}
